<template>
  <div class="user-detail-container">
    <div class="page-header">
      <div class="page-title">用户详情</div>
      <div class="page-actions">
        <el-button @click="goBack">
          <i class="el-icon-back"></i> 返回
        </el-button>
      </div>
    </div>

    <div v-if="loading" style="text-align:center;padding:40px 0;">
      <el-loading></el-loading>
      <div style="margin-top:10px;">正在加载用户信息...</div>
    </div>
    <div v-else-if="error" style="text-align:center;color:#f56c6c;padding:40px 0;">
      <el-icon style="font-size:32px;"><i class="el-icon-warning-outline"></i></el-icon>
      <div style="margin-top:10px;">{{ error }}</div>
    </div>
    <div v-else class="user-info-card">
      <div class="user-basic-info">
        <img :src="'https://randomuser.me/api/portraits/men/65.jpg'" alt="用户头像" class="user-avatar-large">
        <div class="user-basic-details">
          <h2>
            {{ user.user_name || '-' }}
            <el-tag type="success" size="small" v-if="user.is_active">活跃</el-tag>
            <el-tag type="info" size="small" v-else>非活跃</el-tag>
          </h2>
          <p>手机号: {{ user.phonenumber || '-' }}</p>
          <p>注册时间: {{ user.register_at || '-' }}</p>
          <p>用户ID: {{ user.user_id || '-' }}</p>
        </div>
      </div>

      <div class="tabs-container">
        <div class="tab-header">
          <div class="tab-item" :class="{ active: activeTab === 'account' }" @click="activeTab = 'account'">账户安全</div>
          <div class="tab-item" :class="{ active: activeTab === 'behavior' }" @click="activeTab = 'behavior'">行为分析</div>
          <div class="tab-item" :class="{ active: activeTab === 'devices' }" @click="activeTab = 'devices'">设备关联</div>
        </div>

        <div class="tab-pane" :class="{ active: activeTab === 'account' }">
          <div class="form-section">
            <div class="form-row">
              <div class="form-group">
                <label class="form-label">用户名</label>
                <input type="text" class="form-control" :value="user.user_name || '-'" disabled>
              </div>
              <div class="form-group">
                <label class="form-label">手机号</label>
                <input type="tel" class="form-control" :value="user.phonenumber || '-'" disabled>
              </div>
              <div class="form-group">
                <label class="form-label">注册时间</label>
                <input type="text" class="form-control" :value="user.register_at || '-'" disabled>
              </div>
            </div>
          </div>
        </div>

        <div class="tab-pane" :class="{ active: activeTab === 'behavior' }">
          <div class="form-section">
            <h3>听歌记录</h3>
            <div class="date-filter">
              <el-date-picker
                v-model="listenDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleListenDateChange"
              ></el-date-picker>
              <el-button type="primary" size="small" @click="fetchListeningRecords">查询</el-button>
            </div>
            
            <div v-if="listenLoading" style="text-align:center;padding:20px 0;">
              <el-loading></el-loading>
              <div style="margin-top:10px;">正在加载听歌记录...</div>
            </div>
            <div v-else-if="listenError" style="color:#f56c6c;padding:20px 0;">
              <el-icon style="font-size:20px;"><i class="el-icon-warning-outline"></i></el-icon>
              <span style="margin-left:8px;">{{ listenError }}</span>
            </div>
            <div v-else>
              <!-- 总听歌时长 -->
              <el-card shadow="hover" style="margin-bottom:20px;">
                <template #header>听歌总时长</template>
                <div class="total-listen-time">
                  <span class="time-value">{{ formatDuration(yearlyPreferences?.total_duration || dailyListeningDuration?.total_duration || listenData?.total || 0) }}</span>
                </div>
              </el-card>
              
              <!-- 每日听歌时长图表 -->
              <el-card shadow="hover" style="margin-bottom:20px;">
                <template #header>每日听歌时长</template>
                <div v-if="dailyDurationLoading" style="text-align:center;padding:20px 0;">
                  <el-loading></el-loading>
                  <div style="margin-top:10px;">正在加载每日听歌时长数据...</div>
                </div>
                <div v-else style="height:300px;">
                  <div v-if="dailyListeningDuration && dailyListeningDuration.daily_stats" style="height:100%;">
                    <!-- 这里可以用图表库实现可视化，先用表格展示 -->
                    <el-table
                      :data="getFilteredDailyDuration()"
                      size="small"
                      style="width:100%"
                      height="280"
                      :default-sort="{prop: 'date', order: 'descending'}"
                    >
                      <el-table-column prop="date" label="日期" width="120" sortable></el-table-column>
                      <el-table-column prop="duration" label="时长(秒)" width="100" sortable></el-table-column>
                      <el-table-column label="时长">
                        <template #default="scope">
                          {{ formatDuration(scope.row.duration) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="比例">
                        <template #default="scope">
                          <el-progress 
                            :percentage="Math.round((scope.row.duration / Math.max(...getFilteredDailyDuration().map(item => item.duration))) * 100)"
                          ></el-progress>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div v-else-if="listenData && listenData.daily && listenData.daily.length > 0" style="height:100%;">
                    <!-- 使用原有的daily数据作为备选 -->
                    <el-table :data="listenData.daily" size="small" style="width:100%">
                      <el-table-column prop="date" label="日期" width="120"></el-table-column>
                      <el-table-column prop="duration" label="时长(秒)" width="100"></el-table-column>
                      <el-table-column label="时长">
                        <template #default="scope">
                          {{ formatDuration(scope.row.duration) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="比例">
                        <template #default="scope">
                          <el-progress :percentage="Math.round((scope.row.duration / maxDailyDuration) * 100)"></el-progress>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div v-else style="height:100%;display:flex;align-items:center;justify-content:center;background:#f5f7fa;border-radius:4px;">
                    <span>暂无每日听歌数据</span>
                  </div>
                </div>
              </el-card>

              <!-- 时段偏好 -->
              <el-card shadow="hover" style="margin-bottom:20px;">
                <template #header>时段偏好分析</template>
                <div style="min-height:200px;">
                  <div v-if="periodStats && periodStats.period_distribution" style="display:flex;flex-wrap:wrap;gap:20px;">
                    <div style="flex:1;min-width:250px;">
                      <h4>{{ currentYear }}年度时段分布</h4>
                      <el-table :data="formatPeriodDistribution(periodStats.period_distribution)" size="small" style="width:100%">
                        <el-table-column prop="period" label="时段" width="100"></el-table-column>
                        <el-table-column prop="duration" label="时长">
                          <template #default="scope">
                            {{ formatDuration(scope.row.duration) }}
                          </template>
                        </el-table-column>
                        <el-table-column label="比例">
                          <template #default="scope">
                            <el-progress :percentage="scope.row.percentage"></el-progress>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                  <div v-else-if="listenData && listenData.time_preferences" style="display:flex;flex-wrap:wrap;gap:20px;">
                    <div v-for="(timePref, date) in listenData.time_preferences" :key="date" style="flex:1;min-width:250px;">
                      <h4>{{ date }}</h4>
                      <el-table :data="formatTimePreferences(timePref)" size="small" style="width:100%">
                        <el-table-column prop="period" label="时段" width="100"></el-table-column>
                        <el-table-column prop="duration" label="时长">
                          <template #default="scope">
                            {{ formatDuration(scope.row.duration) }}
                          </template>
                        </el-table-column>
                        <el-table-column label="比例">
                          <template #default="scope">
                            <el-progress :percentage="scope.row.percentage"></el-progress>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                  <div v-else style="min-height:200px;display:flex;align-items:center;justify-content:center;background:#f5f7fa;border-radius:4px;">
                    <span>暂无时段偏好数据</span>
                  </div>
                </div>
              </el-card>

              <!-- 分页器 -->
              <div v-if="pagination" class="pagination">
                <el-pagination
                  @size-change="handleListenSizeChange"
                  @current-change="handleListenCurrentChange"
                  :current-page="listenPage"
                  :page-sizes="[5, 10, 20, 50]"
                  :page-size="listenPageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pagination.total_records">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>

        <div class="tab-pane" :class="{ active: activeTab === 'devices' }">
          <div class="form-section">
            <h3>设备关联</h3>
            <div v-if="user.devices && user.devices.length">
              <div v-for="device in user.devices" :key="device.device_id" class="device-card">
                <el-card shadow="hover" style="margin-bottom: 20px;">
                  <template #header>
                    <div class="device-header">
                      <span>设备ID: {{ device.device_id }}</span>
                      <el-tag size="small" type="success" effect="dark" v-if="device.status && device.status.power && device.status.power.state === 'ON'">在线</el-tag>
                      <el-tag size="small" type="info" effect="dark" v-else>离线</el-tag>
                    </div>
                  </template>
                  
                  <div class="device-info">
                    <div class="info-row">
                      <span class="info-label">设备密钥:</span>
                      <span class="info-value">{{ device.device_key }}</span>
                    </div>
                    <div class="info-row">
                      <span class="info-label">绑定时间:</span>
                      <span class="info-value">{{ device.create_at }}</span>
                    </div>
                    
                    <!-- 设备状态信息 -->
                    <div v-if="device.status" class="device-status">
                      <h4>设备状态</h4>
                      
                      <!-- 电源状态 -->
                      <div class="status-section">
                        <h5>电源状态</h5>
                        <div class="info-row">
                          <span class="info-label">电源:</span>
                          <el-tag size="small" type="success" v-if="device.status.power && device.status.power.state === 'ON'">已开启</el-tag>
                          <el-tag size="small" type="info" v-else>已关闭</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">电池电量:</span>
                          <el-progress :percentage="device.status.power ? device.status.power.battery_level || 0 : 0" :color="getBatteryColor(device.status.power ? device.status.power.battery_level || 0 : 0)"></el-progress>
                        </div>
                        <div class="info-row">
                          <span class="info-label">充电状态:</span>
                          <span class="info-value">
                            <i class="el-icon-loading" v-if="device.status.power && device.status.power.charging_state === 'Charging'"></i>
                            {{ getChargingStateText(device.status.power ? device.status.power.charging_state : 'Discharging') }}
                          </span>
                        </div>
                      </div>
                      
                      <!-- 网络状态 -->
                      <div class="status-section">
                        <h5>网络状态</h5>
                        <div class="info-row">
                          <span class="info-label">WiFi状态:</span>
                          <el-tag size="small" type="success" v-if="device.status.network && device.status.network.wifi_state === 'Connected'">已连接</el-tag>
                          <el-tag size="small" type="danger" v-else>未连接</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">网络延迟:</span>
                          <span class="info-value">{{ device.status.network ? (device.status.network.net_delay || 0) : 0 }}ms</span>
                        </div>
                      </div>
                      
                      <!-- 音频状态 -->
                      <div class="status-section">
                        <h5>音频设置</h5>
                        <div class="info-row">
                          <span class="info-label">音效模式:</span>
                          <el-tag size="small" type="primary">{{ device.status.audio ? (device.status.audio.effect || 'common') : 'common' }}</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">播放模式:</span>
                          <el-tag size="small" type="warning">{{ device.status.audio ? (device.status.audio.mode || 'common') : 'common' }}</el-tag>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 当设备状态信息不存在时显示默认状态 -->
                    <div v-else class="device-status">
                      <h4>设备状态</h4>
                      
                      <!-- 默认电源状态 -->
                      <div class="status-section">
                        <h5>电源状态</h5>
                        <div class="info-row">
                          <span class="info-label">电源:</span>
                          <el-tag size="small" type="info">已关闭</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">电池电量:</span>
                          <el-progress :percentage="0" :color="getBatteryColor(0)"></el-progress>
                        </div>
                        <div class="info-row">
                          <span class="info-label">充电状态:</span>
                          <span class="info-value">{{ getChargingStateText('Discharging') }}</span>
                        </div>
                      </div>
                      
                      <!-- 默认网络状态 -->
                      <div class="status-section">
                        <h5>网络状态</h5>
                        <div class="info-row">
                          <span class="info-label">WiFi状态:</span>
                          <el-tag size="small" type="danger">未连接</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">网络延迟:</span>
                          <span class="info-value">0ms</span>
                        </div>
                      </div>
                      
                      <!-- 默认音频状态 -->
                      <div class="status-section">
                        <h5>音频设置</h5>
                        <div class="info-row">
                          <span class="info-label">音效模式:</span>
                          <el-tag size="small" type="primary">common</el-tag>
                        </div>
                        <div class="info-row">
                          <span class="info-label">播放模式:</span>
                          <el-tag size="small" type="warning">common</el-tag>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
            <div v-else style="color:#999;">该用户暂无关联设备</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshUserDetail" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { RefreshRight } from '@element-plus/icons-vue'
// 注释掉以下代码块，使其在没有图表库时不会报错
/*
import VChart from 'vue-echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title'
*/

export default {
  name: 'UserDetail',
  components: {
    // 注释掉VChart组件
    // VChart
    RefreshRight
  },
  data() {
    return {
      activeTab: 'account',
      user: {},
      loading: true,
      error: '',
      userPermissions: [],
      behaviorDateRange: null,
      behaviorType: '',
      securityDateRange: null,
      userProfile: null,
      profileLoading: false,
      profileError: '',
      hourChartData: null,
      styleChartData: null,
      periodChartData: null,
      trendChartData: null,
      listenDateRange: null,
      listenPage: 1,
      listenPageSize: 10,
      listenData: null,
      listenLoading: false,
      listenError: '',
      pagination: null,
      // 新增数据属性
      yearlyPreferences: null,
      periodStats: null,
      currentYear: new Date().getFullYear(),
      // 新增每日听歌时长数据
      dailyListeningDuration: null,
      dailyDurationLoading: false
    }
  },
  created() {
    this.fetchUserDetail();
    // 获取听歌记录
    this.fetchListeningRecords();
    // 获取每日听歌时长
    this.fetchDailyListeningDuration();
  },
  computed: {
    // 计算每日听歌时长最大值，用于进度条展示
    maxDailyDuration() {
      if (!this.listenData || !this.listenData.daily || this.listenData.daily.length === 0) {
        return 0;
      }
      return Math.max(...this.listenData.daily.map(item => item.duration));
    }
  },
  methods: {
    fetchUserDetail() {
      const id = this.$route.params.id
      if (!id) {
        this.error = '未获取到用户ID';
        this.loading = false;
        console.error('用户ID不存在，无法获取用户详情');
        return Promise.resolve();
      }
      this.loading = true;
      
      // 使用指定的API路径
      const apiUrl = `https://smartsound.top/api/v1/admin/userdetail?user_id=${id}`;
      console.log('开始请求用户详情, ID:', id);
      console.log('请求URL:', apiUrl);
      
      // 添加请求配置，包含headers
      const config = {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      };
      
      return axios.get(apiUrl, config)
        .then(res => {
          console.log('API返回用户数据:', JSON.stringify(res.data));
          if (res.data.code === 0) {
            this.user = res.data.data || {};
            this.user.devices = this.user.devices || [];
            this.user.play_history = this.user.play_history || [];
            this.error = '';
            console.log('用户数据已设置:', this.user);
            
            // 获取用户偏好数据
            this.fetchUserPreferences();
            // 获取时段统计数据
            this.fetchPeriodStats();
          } else {
            this.error = res.data.message || '获取用户详情失败';
          }
        })
        .catch((error) => {
          console.error('获取用户详情失败:', error);
          this.error = '获取用户详情失败，请检查网络连接';
        })
        .finally(() => {
          this.loading = false;
          console.log('用户详情请求完成，loading状态:', this.loading);
        });
    },
    
    // 获取用户偏好数据
    fetchUserPreferences() {
      const id = this.$route.params.id;
      if (!id) return;
      
      const apiUrl = `https://smartsound.top/api/v1/music_preferences?user_id=${id}&year=${this.currentYear}`;
      console.log('开始请求用户偏好数据, URL:', apiUrl);
      
      axios.get(apiUrl)
        .then(res => {
          console.log('用户偏好数据响应:', res.data);
          if (res.data.code === 0 && res.data.data && res.data.data.length > 0) {
            this.yearlyPreferences = res.data.data[0];
            console.log('用户偏好数据已设置:', this.yearlyPreferences);
            
            // 更新用户画像数据
            this.updateUserProfile();
          }
        })
        .catch(error => {
          console.error('获取用户偏好数据失败:', error);
        });
    },
    
    // 获取时段统计数据
    fetchPeriodStats() {
      const id = this.$route.params.id;
      if (!id) return;
      
      const apiUrl = `https://smartsound.top/api/v1/get_period_stats?user_id=${id}&year=${this.currentYear}`;
      console.log('开始请求时段统计数据, URL:', apiUrl);
      
      axios.get(apiUrl)
        .then(res => {
          console.log('时段统计数据响应:', res.data);
          if (res.data.code === 0 && res.data.data && res.data.data.length > 0) {
            this.periodStats = res.data.data[0];
            console.log('时段统计数据已设置:', this.periodStats);
            
            // 更新图表数据
            this.updateChartData();
          }
        })
        .catch(error => {
          console.error('获取时段统计数据失败:', error);
        });
    },
    
    // 根据获取的数据更新用户画像
    updateUserProfile() {
      if (!this.yearlyPreferences) return;
      
      // 构建用户画像数据
      const preferences = this.yearlyPreferences;
      
      // 获取最常听的风格
      let topStyles = [];
      if (preferences.style_preferences) {
        topStyles = Object.entries(preferences.style_preferences)
          .sort((a, b) => b[1] - a[1])
          .slice(0, 3)
          .map(item => item[0]);
      }
      
      // 构建用户画像
      this.userProfile = {
        portrait: `偏好${topStyles.join('、')}等音乐风格的用户`,
        analysis: `该用户总听歌时长为${this.formatDuration(preferences.total_duration || 0)}，主要偏好${topStyles.join('、')}等音乐风格。`,
        stats: {
          listening_patterns: {
            continuity_score: 7.5, // 示例数据
            regularity_score: 0.85,
            avg_interval: 240
          }
        },
      };
      
      this.profileError = '';
    },
    
    // 更新图表数据
    updateChartData() {
      if (!this.yearlyPreferences || !this.periodStats) return;
      
      // 构建时段分布图表数据
      this.periodChartData = {
        labels: ['早晨', '下午', '傍晚', '夜间'],
        values: [
          this.periodStats.period_distribution?.morning || 0,
          this.periodStats.period_distribution?.afternoon || 0,
          this.periodStats.period_distribution?.evening || 0,
          this.periodStats.period_distribution?.night || 0
        ]
      };
      
      // 构建风格偏好图表数据
      if (this.yearlyPreferences.style_preferences) {
        const styleData = Object.entries(this.yearlyPreferences.style_preferences)
          .sort((a, b) => b[1] - a[1])
          .slice(0, 10);
          
        this.styleChartData = {
          labels: styleData.map(item => item[0]),
          values: styleData.map(item => item[1])
        };
      }
      
      console.log('图表数据已更新:', {
        period: this.periodChartData,
        style: this.styleChartData
      });
    },
    
    // 获取听歌记录
    fetchListeningRecords() {
      const id = this.$route.params.id
      if (!id) {
        this.listenError = '未获取到用户ID';
        this.listenLoading = false;
        console.error('用户ID不存在，无法获取听歌记录');
        return;
      }
      
      this.listenLoading = true;
      
      // 构建API请求URL
      let apiUrl = `https://smartsound.top/api/v1/records?user_id=${id}&page=${this.listenPage}&page_size=${this.listenPageSize}`;
      
      // 如果有日期筛选，添加日期参数
      if (this.listenDateRange && this.listenDateRange.length === 2) {
        const startDate = this.formatDate(this.listenDateRange[0]);
        const endDate = this.formatDate(this.listenDateRange[1]);
        apiUrl += `&start_date=${startDate}&end_date=${endDate}`;
      }
      
      console.log('开始请求听歌记录, URL:', apiUrl);
      
      // 添加请求配置，包含headers
      const config = {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      };
      
      axios.get(apiUrl, config)
        .then(res => {
          console.log('听歌记录响应:', res.data);
          if (res.data.code === 0) {
            // 处理新的API响应格式
            this.pagination = res.data.pagination;
            
            // 处理记录数据
            const records = res.data.records || [];
            
            // 计算总时长
            const totalDuration = records.reduce((sum, record) => sum + (record.duration || 0), 0);
            
            // 按日期分组
            const dailyData = {};
            const timePreferences = {};
            const stylePreferences = {};
            
            // 当前日期作为默认键
            const today = this.formatDate(new Date());
            dailyData[today] = 0;
            timePreferences[today] = {
              morning: 0,
              afternoon: 0,
              evening: 0,
              night: 0
            };
            stylePreferences[today] = {};
            
            // 处理每条记录
            records.forEach(record => {
              // 提取日期
              const date = record.date || today;
              
              // 累加每日时长
              if (!dailyData[date]) {
                dailyData[date] = 0;
              }
              dailyData[date] += record.duration || 0;
              
              // 累加时段偏好
              if (!timePreferences[date]) {
                timePreferences[date] = {
                  morning: 0,
                  afternoon: 0,
                  evening: 0,
                  night: 0
                };
              }
              const period = record.period || 'morning';
              timePreferences[date][period] += record.duration || 0;
              
              // 累加风格偏好
              if (!stylePreferences[date]) {
                stylePreferences[date] = {};
              }
              
              // 处理多个风格
              if (record.styles && record.styles.length > 0) {
                record.styles.forEach(style => {
                  if (!stylePreferences[date][style]) {
                    stylePreferences[date][style] = 0;
                  }
                  stylePreferences[date][style] += record.duration || 0;
                });
              }
            });
            
            // 转换为数组格式用于表格显示
            const dailyArray = Object.entries(dailyData).map(([date, duration]) => ({
              date,
              duration
            }));
            
            // 设置数据
            this.listenData = {
              total: totalDuration,
              daily: dailyArray,
              time_preferences: timePreferences,
              style_preferences: stylePreferences,
              records: records
            };
            
            this.listenError = '';
            console.log('听歌记录数据已设置:', this.listenData);
          } else {
            // 如果API返回错误
            this.listenError = res.data.message || '获取听歌记录失败';
            console.warn('API返回错误:', res.data);
          }
        })
        .catch((error) => {
          console.error('获取听歌记录失败:', error);
          this.listenError = '获取听歌记录失败，请检查网络连接';
        })
        .finally(() => {
          this.listenLoading = false;
        });
    },
    formatTime(ts) {
      if (!ts) return '-';
      // 支持 ISO/UTC 字符串
      const d = new Date(ts);
      if (isNaN(d.getTime())) return ts;
      const y = d.getFullYear();
      const m = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const h = d.getHours().toString().padStart(2, '0');
      const min = d.getMinutes().toString().padStart(2, '0');
      const s = d.getSeconds().toString().padStart(2, '0');
      return `${y}-${m}-${day} ${h}:${min}:${s}`;
    },
    goBack() {
      this.$router.back();
    },
    // 格式化日期 YYYY-MM-DD
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 格式化时长 秒 -> 时:分:秒
    formatDuration(seconds) {
      if (!seconds) return '0秒';
      
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const remainingSeconds = Math.floor(seconds % 60);
      
      let result = '';
      if (hours > 0) {
        result += `${hours}小时`;
      }
      if (minutes > 0) {
        result += `${minutes}分钟`;
      }
      if (remainingSeconds > 0 || result === '') {
        result += `${remainingSeconds}秒`;
      }
      
      return result;
    },
    
    // 处理听歌记录日期筛选变更
    handleListenDateChange() {
      console.log('日期筛选变更:', this.listenDateRange);
      // 强制更新视图，以刷新筛选后的每日听歌时长数据
      this.$forceUpdate();
    },
    
    // 处理分页大小变更
    handleListenSizeChange(size) {
      this.listenPageSize = size;
      this.fetchListeningRecords();
    },
    
    // 处理页码变更
    handleListenCurrentChange(page) {
      this.listenPage = page;
      this.fetchListeningRecords();
    },
    
    // 格式化时段偏好数据为表格数据
    formatTimePreferences(timePref) {
      if (!timePref) return [];
      
      // 计算总时长
      const total = Object.values(timePref).reduce((sum, duration) => sum + duration, 0);
      
      // 翻译时段名称
      const periodTranslations = {
        morning: '早晨',
        afternoon: '下午',
        evening: '傍晚',
        night: '夜间'
      };
      
      // 转换为表格数据
      return Object.entries(timePref).map(([period, duration]) => ({
        period: periodTranslations[period] || period,
        duration: duration,
        percentage: Math.round((duration / total) * 100)
      }));
    },
    
    // 格式化风格偏好数据为表格数据
    formatStylePreferences(stylePref) {
      if (!stylePref) return [];
      
      // 计算总时长
      const total = Object.values(stylePref).reduce((sum, duration) => sum + duration, 0);
      
      // 转换为表格数据
      return Object.entries(stylePref).map(([style, duration]) => ({
        style: style,
        duration: duration,
        percentage: Math.round((duration / total) * 100)
      }));
    },
    
    // 格式化年度风格偏好数据为表格数据
    formatStylePreferencesYearly(stylePref) {
      if (!stylePref) return [];
      
      // 计算总时长
      const total = Object.values(stylePref).reduce((sum, duration) => sum + duration, 0);
      
      // 转换为表格数据，并按时长降序排序
      return Object.entries(stylePref)
        .map(([style, duration]) => ({
          style: style,
          duration: duration,
          percentage: Math.round((duration / total) * 100)
        }))
        .sort((a, b) => b.duration - a.duration);
    },
    
    // 格式化时段分布数据为表格数据
    formatPeriodDistribution(periodDist) {
      if (!periodDist) return [];
      
      // 计算总时长
      const total = Object.values(periodDist).reduce((sum, duration) => sum + duration, 0);
      
      // 翻译时段名称
      const periodTranslations = {
        morning: '早晨',
        afternoon: '下午',
        evening: '傍晚',
        night: '夜间'
      };
      
      // 转换为表格数据
      return Object.entries(periodDist).map(([period, duration]) => ({
        period: periodTranslations[period] || period,
        duration: duration,
        percentage: Math.round((duration / total) * 100)
      }));
    },
    
    // 获取电池颜色
    getBatteryColor(level) {
      if (level <= 20) {
        return '#F56C6C'; // 红色，低电量
      } else if (level <= 50) {
        return '#E6A23C'; // 橙色，中等电量
      } else {
        return '#67C23A'; // 绿色，高电量
      }
    },
    
    // 获取充电状态文本
    getChargingStateText(state) {
      switch (state) {
        case 'Charging':
          return '充电中';
        case 'Discharging':
          return '放电中';
        case 'Full':
          return '电量已满';
        default:
          return state;
      }
    },
    // 获取每日听歌时长
    fetchDailyListeningDuration() {
      const id = this.$route.params.id;
      if (!id) return;
      
      this.dailyDurationLoading = true;
      
      // 使用正确的API URL
      const apiUrl = `https://smartsound.top/api/v1/listening_duration?user_id=${id}`;
      console.log('开始请求每日听歌时长数据, URL:', apiUrl);
      
      axios.get(apiUrl)
        .then(res => {
          console.log('每日听歌时长数据响应:', res.data);
          if (res.data.code === 0 && res.data.data && res.data.data.length > 0) {
            this.dailyListeningDuration = res.data.data[0];
            console.log('每日听歌时长数据已设置:', this.dailyListeningDuration);
          }
        })
        .catch(error => {
          console.error('获取每日听歌时长数据失败:', error);
        })
        .finally(() => {
          this.dailyDurationLoading = false;
        });
    },
    
    // 根据日期范围筛选每日听歌时长数据
    getFilteredDailyDuration() {
      if (!this.dailyListeningDuration || !this.dailyListeningDuration.daily_stats) {
        return [];
      }
      
      const dailyStats = this.dailyListeningDuration.daily_stats;
      let filteredData = Object.entries(dailyStats).map(([date, duration]) => ({
        date,
        duration
      }));
      
      // 如果有日期筛选，则过滤数据
      if (this.listenDateRange && this.listenDateRange.length === 2) {
        const startDate = this.formatDate(this.listenDateRange[0]);
        const endDate = this.formatDate(this.listenDateRange[1]);
        
        filteredData = filteredData.filter(item => {
          return item.date >= startDate && item.date <= endDate;
        });
      }
      
      // 按日期排序
      filteredData.sort((a, b) => a.date.localeCompare(b.date));
      
      return filteredData;
    },
    refreshUserDetail() {
      this.fetchUserDetail();
      this.fetchListeningRecords();
      this.fetchDailyListeningDuration();
    }
  }
}
</script>

<style scoped>
body {
  background-color: #f5f7fa;
  color: #333;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.user-detail-container {
  margin: 0;
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
}

.page-actions {
  display: flex;
}

.page-actions button {
  margin-left: 10px;
}

.user-info-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.user-basic-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar-large {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 30px;
}

.user-basic-details h2 {
  margin-bottom: 10px;
  font-size: 20px;
}

.user-basic-details p {
  color: #666;
  margin-bottom: 5px;
}

.tabs-container {
  margin-bottom: 20px;
}

.tab-pane {
  display: none;
  padding: 15px 0;
}

.tab-pane.active {
  display: block;
}

.tab-header {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 15px;
}

.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
}

.tab-item.active {
  border-bottom-color: #1890ff;
  color: #1890ff;
  font-weight: bold;
}

.form-section {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-group {
  flex: 1;
  min-width: 300px;
  margin-right: 20px;
  margin-bottom: 15px;
}

.form-group:last-child {
  margin-right: 0;
}

.form-label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #666;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
}

.form-control:focus {
  border-color: #1890ff;
}

.form-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.timeline-item {
  position: relative;
  padding-left: 30px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.timeline-item:before {
  content: '';
  position: absolute;
  left: 10px;
  top: 0;
  bottom: -20px;
  width: 2px;
  background-color: #e8e8e8;
}

.timeline-dot {
  position: absolute;
  left: 5px;
  top: 5px;
  width: 14px;
  height: 14px;
  background-color: #1890ff;
  border-radius: 50%;
  z-index: 1;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.timeline-title {
  font-weight: bold;
}

.timeline-time {
  color: #999;
  font-size: 12px;
}

.timeline-content {
  color: #666;
  line-height: 1.5;
}

/* 设备关联图样式 */
.device-map {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.device-map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.device-map-title {
  font-size: 16px;
  font-weight: bold;
}

.map-controls {
  display: flex;
}

.map-controls button {
  margin-left: 10px;
}

.map-container {
  height: 400px;
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

/* 行为分析时间轴样式 */
.behavior-timeline {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.timeline-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.timeline-range {
  display: flex;
  align-items: center;
}

.timeline-range span {
  margin: 0 10px;
}

/* 安全信息时间线样式 */
.security-timeline {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.security-level {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: white;
}

.level-low {
  background-color: #90ee90;
}

.level-medium {
  background-color: #ffd700;
}

.level-high {
  background-color: #ff6b6b;
}

.date-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.date-filter .el-button {
  margin-left: 10px;
}

.total-listen-time {
  text-align: center;
  padding: 20px 0;
}

.time-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 设备卡片样式 */
.device-card {
  margin-bottom: 20px;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-info {
  padding: 10px 0;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-label {
  min-width: 80px;
  color: #606266;
  font-weight: bold;
}

.info-value {
  flex: 1;
}

.device-status {
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.status-section {
  margin-bottom: 15px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.status-section h5 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
  font-size: 14px;
}

/* 浮动操作区样式 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  border-radius: 50% !important;
  width: 52px !important;
  height: 52px !important;
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  background: linear-gradient(45deg, #1890ff, #40a9ff) !important;
  border-color: transparent !important;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4) !important;
  transition: all 0.3s !important;
}

.refresh-btn:hover {
  transform: translateY(-5px) scale(1.05) !important;
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.5) !important;
}

.refresh-btn .el-icon {
  font-size: 24px !important;
  margin-right: 0 !important;
}
</style>